{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Machine Learning at Scale, Part II"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For this tutorial, we'll dig deeper into BIDMach's learning architecture. The examples so far have use convenience functions which assembled together a Data Source, Learner, Model, Updater and Mixin classes to make a trainable model. This time we'll separate out those components and see how they can be customized. \n",
    "\n",
    "The dataset is from UCI and comprises Pubmed abstracts. It is about 7.3GB in text form. We'll compute an LDA topic model for this dataset. \n",
    "\n",
    "First lets initialize BIDMach again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import $exec.^.lib.bidmach_notebook_init\n",
    "if (Mat.hasCUDA > 0) GPUmem"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Check the GPU memory again, and make sure you dont have any dangling processes."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Large-scale Topic Models"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A **Topic model** is a representation of a Bag-Of-Words corpus as several factors or topics. Each topic should represent a theme that recurs in the corpus. Concretely, the output of the topic model will be an (ntopics x nfeatures) matrix we will call <code>tmodel</code>. Each row of that matrix represents a topic, and the elements of that row are word probabilities for the topic (i.e. the rows sum to 1). There is more about topic models <a href=\"http://en.wikipedia.org/wiki/Topic_model\">here on wikipedia</a>.\n",
    "\n",
    "The **element <code>tmodel(i,j)</code> holds the probability that word j belongs to topic i**. Later we will examine the topics directly and try to make sense of them.\n",
    "\n",
    "Lets construct a learner with a files data source. Most model classes will accept a String argument, and assume it is a pattern for accessing a collection of files. To create the learner, we pass this pattern (which will be invoked with <string> format i) to enumerate one filename. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val mdir = \"../data/uci/pubmed_parts/\";\n",
    "val (nn, opts) = LDA.learner(mdir+\"part%02d.smat.lz4\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that this dataset is quite large, and isnt one of the ones loaded by <code>getdata.sh</code> in the <code>scripts</code> directory. You need to run the script <code>getpubmed.sh</code> separately (and plan a long walk or bike ride while you wait...). \n",
    "\n",
    "This datasource uses just this sequence of files, and each matrix has 141043 rows. A number of options are listed below that control the files datasource. Most of these dont need to be set (you'll notice they're just set to their default values), but its useful to know about them for customizing data sources. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "opts.nstart = 0;                 // Starting file number\n",
    "opts.nend = 10;                  // Ending file number\n",
    "opts.order = 0;                  // (0) sample order, 0=linear, 1=random\n",
    "opts.lookahead = 2;              // (2) number of prefetch threads\n",
    "opts.featType = 1;               // (1) feature type, 0=binary, 1=linear\n",
    "// These are specific to SfilesSource:\n",
    "opts.eltsPerSample = 400         // how many rows to allocate (non-zeros per sample)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We're ready to go. LDA is a popular topic model, described <a href=\"http://en.wikipedia.org/wiki/Latent_Dirichlet_allocation\">here on wikipedia</a>.\n",
    "\n",
    "We use a fast version of LDA which uses an incremental multiplicative update described by Hoffman, Blei and Bach \n",
    "<a href=\"https://www.cs.princeton.edu/~blei/papers/HoffmanBleiBach2010b.pdf\">here</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Tuning Options"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add tuning options for minibatch size (say 100k), number of passes (4) and dimension (<code>dim = 256</code>). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "opts.batchSize=20000\n",
    "opts.npasses=2\n",
    "opts.dim=256"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You invoke the learner the same way as before. You can change the options above after each run to optimize performance. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nn.train"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each training run creates a <code>results</code> matrix which is essentially a graph of the log likelihood vs number of input samples. The first row is the likelihood values, the second is the corresponding number of input samples procesed. We can plot the results here:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot(nn.results(1,?), nn.results(0,?))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To evaluate the model, we save the model matrix itself, and also load a dictionary of the terms in the corpus."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val tmodel = FMat(nn.modelmat)\n",
    "val dict = Dict(loadSBMat(mdir+\"../pubmed.term.sbmat.lz4\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The dictionary allows us to look up terms by their index, e.g. <code>dict(1000)</code>, by their string represenation <code>dict(\"book\")</code>, and by matrices of these, e.g. <code>dict(ii)</code> where <code>ii</code> is an IMat. Try a few such queries to the dict here:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next we evaluate the entropy of each dimension of the model. Recall that the entropy of a discrete probability distribution is $E = -\\sum_{i=1}^n p_i \\ln(p_i)$. The rows of the matrix are the topic probabilities.\n",
    "\n",
    "Compute the entropies for each topic:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val ent = -(tmodel dotr ln(tmodel))\n",
    "ent.t // put them in a horizontal line"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Get the mean value (should be positive)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mean(ent)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Find the smallest and largest entropy topic indices (use maxi2 and mini2). Call them <code>elargest</code> and <code>esmallest</code>."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val (vlargest,elargest) = maxi2(ent)\n",
    "val (vsmallest,esmallest) = mini2(ent)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we'll sort the probabilities within each topic to bring the highest probability terms to the beginning. We sort down (descending order) along dimension 2 (rows) to do this. <code>bestv</code> gets the sorted values and <code>besti</code> gets the sorted indices which are the feature indices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val (bestp, besti) = sortdown2(tmodel,2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now examine the 100 strongest terms in each topic:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dict(besti(elargest,0->100))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dict(besti(esmallest,0->100))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Do you notice any difference in the coherence of these two topics?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> TODO: Fill in your answer here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By sorting the entropies, find the 2nd and 3rd smallest entropy topics. Give the top 100 terms in each topic below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val (sent, ient) = sort2(ent)\n",
    "// words for 2nd lowest entropy topic\n",
    "dict(besti(ient(1),0->100))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "// words for 3rd lowest entropy topic\n",
    "dict(besti(ient(2),0->100))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Running more topics"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What would you expect to happen to the average topic entropy if you run fewer topics? "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> TODO: answer here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Change the opts.dim argument above and try it. First note the entropy at dim = 256 below. Then run again with <code>dim=64</code> and put the new value below: "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table>\n",
    "<tr>\n",
    "<th>dim</th>\n",
    "<th>mean entropy</th>\n",
    "</tr>\n",
    "<tr>\n",
    "<td>64</td>\n",
    "<td>...</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td>256</td>\n",
    "<td>...</td>\n",
    "</tr>\n",
    "</table>\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".scala",
   "mimetype": "text/x-scala",
   "name": "scala211",
   "nbconvert_exporter": "script",
   "pygments_lexer": "scala",
   "version": "2.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
